package com.amlyc.ch04;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class AtomicIntegerFieldUpdaterDemo {
    public static class Candidate{
        int id;
        volatile int score;
    }

    public final static AtomicIntegerFieldUpdater<Candidate> score = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
    public static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {

        final Candidate stu = new Candidate();
        Thread[] threads = new Thread[1000];
        for (int i = 0; i < 1000; i++) {
            threads[i] = new Thread(()->{
                if (Math.random() > 0.4) {
                    score.incrementAndGet(stu);
                    atomicInteger.incrementAndGet();
                }
            });
            threads[i].start();
        }
        for (int i = 0; i < 1000; i++) {
            threads[i].join();
        }
        System.out.println(stu.score);
        System.out.println(atomicInteger);

    }

}
